package zhai.docking.alipay.service.base.alipay.api.notify;

import com.alipay.api.msg.AlipayMsgClient;
import com.alipay.api.msg.MsgHandler;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zhai.docking.alipay.constant.AlipayConstant;
import zhai.docking.alipay.constant.LogConstant;
import zhai.docking.alipay.domain.base.alipay.BaseAlipayApiMessage;
import zhai.docking.alipay.domain.base.bizlog.BizLogDataTemp;
import zhai.docking.alipay.domain.base.bizlog.BizLogSave;
import zhai.docking.alipay.prop.AlipayApiProperties;
import zhai.docking.alipay.service.base.bizlog.BizLogSer;
import zhai.docking.alipay.util.JSONUtil;
import zhai.docking.alipay.util.StringUtil;

/**
 * @author Created by 翟凤玺
 * @package zhai.docking.alipay.service.base.alipay.api.notify
 * @project-name zhai-docking-alipay
 * @description 基础-支付宝-通知 服务实现
 * @create-datetime 2021/1/6 11:00
 */
@Slf4j
@Service
public class BaseAlipayApiNotifySerImpl implements BaseAlipayApiNotifySer {

    private static final String BUSINESS_NAME = "【基础-支付宝-通知 服务】";
    private static final String METHOD_ALIPAY_MESSAGE = "（消息）";

    @Autowired
    AlipayApiProperties alipayApiProp;
    @Autowired
    BizLogSer bizLogSer;

    @SneakyThrows
    @Override
    public String alipayMessage() {
        log.info(StringUtil.join(BUSINESS_NAME, LogConstant.SERVICE, METHOD_ALIPAY_MESSAGE));
        AlipayMsgClient alipayMsgClient = AlipayMsgClient.getInstance(alipayApiProp.getAppid());
        alipayMsgClient.setConnector(AlipayConstant.COMMON_MESSAGE_SERVER_URL);
        alipayMsgClient.setSecurityConfig(AlipayConstant.COMMON_SIGN_TYPE, alipayApiProp.getPrivateKey(), alipayApiProp.getPublicKey());
        alipayMsgClient.setMessageHandler(new MsgHandler() {
            /**
             * 客户端接收到消息后回调此方法
             * @param msgApi 接收到的消息的消息api名
             * @param msgId 接收到的消息的消息id
             * @param bizContent 接收到的消息的内容，json格式
             */
            @Override
            public void onMessage(String msgApi, String msgId, String bizContent) {
                /** 操作：记录业务日志 */
                BaseAlipayApiMessage message = new BaseAlipayApiMessage();
                message.setMsgApi(msgApi);
                message.setMsgId(msgId);
                message.setBizContent(bizContent);
                bizLogSer.save(new BizLogSave(new BizLogDataTemp(message, null), AlipayConstant.MESSAGE_LOG));

            }
        });
        alipayMsgClient.connect();
        return JSONUtil.toStr(alipayMsgClient);
    }
}